import React, { PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import {
 Form, Input, message, Tabs, Upload, Switch,
} from 'antd'
import _ from 'lodash'
import moment from 'moment'
import {
 BreadcrumbBar, CreateDiffEditor, ProTable, ProTableOptions,
} from '@/components'
import { setCopy } from '@/components/CopyText'
import { regExp } from '@/utils/regExp'
import { getProjectId, SUAN_PAN } from '@/utils/https'
import { getHashParameterByName } from '@/utils/helper'
import styles from './index.less'

const { Item } = Form
const { TabPane } = Tabs
const { Dragger } = Upload

const descType = window.location.hash?.split('&type=')?.[1]
const calcMenu = () => {
  let str = ''
  if (descType === 'my') {
    str = '我的API'
  }
  if (descType === 'market') {
    str = 'API市场'
  }
  if (descType === 'apply') {
    str = '我的申请'
  }
  return str
}

const menus = [{ name: calcMenu() }, { name: 'API详情' }]
const lenRe = regExp.proName(1, 128)

const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = dataIndex === 'operation' ? inputType(record) : (
    <Form.Item
      name={dataIndex}
      style={{ margin: 0 }}
      rules={[
        {
          required: true,
          message: `请输入${title}`,
        },
        {
          pattern: new RegExp(lenRe.reg, 'g'),
          message: lenRe.text,
        },
      ]}
    >
      <Input placeholder={`请输入${title}`} />
    </Form.Item>
  )

  return (
    <td {...restProps}>
      {editing ? (
        inputNode
      ) : (
        children
      )}
    </td>
  )
}

@connect(({ registerApiCreate }) => ({ ...registerApiCreate }))
class RegisterApiDetail extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      // requestParams: [], // 请求参数设置 数据源
      activeTabKey: '1',
      fileList: [],
      headerColumns: [
        {
          title: '参数名称',
          dataIndex: 'fieldName',
          width: '35%',
          key: 'fieldName',
          editable: true,
        },
        {
          title: '参数值',
          dataIndex: 'fieldValue',
          width: '35%',
          key: 'fieldValue',
          editable: true,
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '30%',
          key: 'operation',
          editable: true,
          inputType: (record) => (
            <ProTableOptions>
              <span onClick={this.onFieldSaveClick}>保存</span>
              {
                // 此处作删除使用
                (!record.fieldName || record.fieldName === '') ? (
                  <span onClick={() => { this.onDelClick(record) }}>取消</span>
                ) : (
                  <span onClick={this.onFieldCancelClick}>取消</span>
                )
              }
            </ProTableOptions>
          ),
          render: () => (
            <ProTableOptions>
              <span className={styles.disabled}>编辑</span>
              <span className={styles.disabled}>删除</span>
            </ProTableOptions>
          ),
        },
      ],
      requestHeaderData: [],
      rawJson: '',
    }

    this.editorObjectEditId = `${Math.random()}`
    this.dataSourceForm = React.createRef()
    this.tableData = React.createRef()
    this.objectParamsRef = React.createRef()
  }

  componentDidMount() {
    this.descId = getHashParameterByName('id')
    this.descType = getHashParameterByName('type')
    this.descId && this.viewDetail(this.descId)
  }

  // 查看详情
  viewDetail = (id) => {
    this.props.dispatch({
      type: 'registerApiCreate/queryGetDataApiDetailById',
      params: {
        id,
      },
      cb: (res) => {
        const { status, msg, data = {} } = res || {}
        if (status === 200) {
          const {
            apiName, apiPath, apiProtocol, apiMethod, apiDesc, dataApiRegisterDomain, apiGroup, prodApiUrl, testApiUrl, authType, isSecurity,
          } = data

          const {
            apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader, httpRequestMethod, url,
          } = dataApiRegisterDomain || {}

          this.setState({
            apiName,
            apiPath,
            apiProtocol,
            apiMethod,
            apiDesc,
            httpRequestMethod,
            authType1: authType,
            url,
            apiGroup,
            prodApiUrl,
            testApiUrl,
            isSecurity,
          })
          this.initParams(apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader)
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  // 初始化页面参数
  initParams = (apiHttpAuth, apiHttpRequestBody, apiHttpRequestHeader) => {
    const { params } = apiHttpRequestHeader || {}
    const requestHeaderData = []
    params?.map((item, index) => {
      requestHeaderData.push({
        fieldName: item.name,
        fieldValue: item.value,
        key: index,
      })
      return null
    })

    const { body = '' } = apiHttpRequestBody || {}
    this.setState({
      requestHeaderData,
      rawJson: body,
    })

    // 认证类型为 自定义文件 的情况
    const {
      authType, advancedFileName, expires,
    } = apiHttpAuth || {}
    if (authType === 'jar') {
      const tempExpires = expires && moment(expires, 'YYYY-MM-DD')
      // this.dataSourceForm.current.setFieldsValue({ expires: tempExpires })

      this.setState({
        fileList: [{
          uid: Math.random(),
          name: advancedFileName,
          status: 'done',
        }],
        expires: tempExpires,
      })
    }

    const fieldObj = {
      ...apiHttpAuth,
      ...apiHttpRequestBody,
    }

    if (fieldObj?.expires) {
      // delete fieldObj.expires
    }

    this.setState({
      ...fieldObj,
    })
  }

  // 删除参数按钮回调
  onDelClick = (record) => {
    const arr = []
    this.state.requestHeaderData.map((item) => {
      if (item.key !== record.key) {
        arr.push(item)
      }
      return null
    })
    // 删除时按顺序重置key
    arr.map((item, index) => {
      item.key = index
      return null
    })
    this.setState({
      requestHeaderData: arr,
      editingKey: undefined,
    })
  }

  // 保存参数修改
  onFieldSaveClick = () => {
    this.tableData.current.validateFields().then(values => {
      const { requestHeaderData, editingKey } = this.state
      const dataObj = requestHeaderData.find((item) => item.key === editingKey)
      dataObj.fieldName = values.fieldName
      dataObj.fieldValue = values.fieldValue
      this.setState({
        editingKey: undefined,
        requestHeaderData: _.clone(requestHeaderData),
      })
    })
  }

  // 取消参数修改
  onFieldCancelClick = () => {
    const { requestHeaderData } = this.state
    this.setState({
      editingKey: undefined,
      requestHeaderData: _.clone(requestHeaderData),
    })
  }

  goBack = () => {
    if (this.descType === 'my') {
      history.push('/data-service/api-manage/my-api')
      return null
    }
    if (this.descType === 'market') {
      history.push('/data-service/api-market')
      return null
    }
    if (this.descType === 'apply') {
      history.push('/data-service/api-manage/my-apply')
      return null
    }
    return null
  }

  render() {
    const {
      fileList, activeTabKey, headerColumns, requestHeaderData, rawJson, apiPath, apiProtocol, apiMethod, apiDesc, apiName,
      httpRequestMethod, url, expires, authType, authType1, accessKey, accessSecret, accessToken, advanceClassReference,
      advanceMethodName, contentType, apiGroup, prodApiUrl, testApiUrl, isSecurity,
    } = this.state
    return (
      <div className={styles.my_api_create}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.back_bar}>
          <i
            className="iconfont icon-zuo"
            onClick={this.goBack}
            style={{ cursor: 'pointer' }}
          />
          <span onClick={this.goBack}>查看</span>
        </div>
        <div className={styles.container}>
          <Form
            ref={this.dataSourceForm}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 10 }}
            autoComplete="off"
          >
            <Item>
              <div className={styles.column}>基础设置</div>
            </Item>
            <Item
              label="API名称"
              name="apiName"
            >
              <div className={styles.cont}>{apiName || '-'}</div>
            </Item>
            <Item
              label="API Path"
              name="apiPath"
            >
              <div className={styles.cont}>
                {apiPath || '-'}
                {
                  apiPath && (<i
                    className="iconfont icon-fuzhi"
                    onClick={() => { setCopy(apiPath) }}
                  />)
                }
              </div>
            </Item>
            <Item
              label="API协议"
              name="apiProtocol"
            >
              <div className={styles.cont}>{['HTTP', 'HTTPS'][apiProtocol] || '-'}</div>
            </Item>
            <Item
              label="请求方式"
              name="apiMethod"
            >
              <div className={styles.cont}>{apiMethod || '-'}</div>
            </Item>
            <Item
              label="认证方式"
              name="authType1"
            >
              <div className={styles.cont}>{authType1 == 1 ? 'UserToken认证' : 'ApiToken认证'}</div>
            </Item>
            <Item
              label="API测试路径"
              name="testApiUrl"
            >
              <div className={styles.cont} title={testApiUrl}>
                <span className={styles.text_overflow_single} style={{ width: '95%', display: 'inline-block', lineHeight: '0.2rem' }}>{testApiUrl || '-'}</span>
                {
                  testApiUrl && (<i
                    className="iconfont icon-fuzhi"
                    onClick={() => { setCopy(testApiUrl) }}
                  />)
                }
              </div>
            </Item>
            <Item
              label="API生产路径"
              name="prodApiUrl"
            >
              <div className={styles.cont} title={prodApiUrl}>
                <span className={styles.text_overflow_single} style={{ width: '95%', display: 'inline-block', lineHeight: '0.2rem' }}>{prodApiUrl || '-'}</span>
                {
                  prodApiUrl && (<i
                    className="iconfont icon-fuzhi"
                    onClick={() => { setCopy(prodApiUrl) }}
                  />)
                }
              </div>
            </Item>
            <Item
              label="API分组"
              name="apiGroupId"
            >
              <div className={styles.cont}>{apiGroup || '-'}</div>
            </Item>
            <Item
              label="出入参是否加密"
              name="isSecurity"
            >
              <Switch checked={!!isSecurity} disabled />
            </Item>
            <Item
              label="描述"
              name="apiDesc"
            >
              <div className={`${styles.cont} ${styles.height}`}>{apiDesc || '-'}</div>
            </Item>
            <Item>
              <div className={styles.column}>后端服务接口</div>
            </Item>
            {/* 后端让去掉 */}
            {/* <Item */}
            {/*  label="协议" */}
            {/*  name="apiProtocol2" */}
            {/* > */}
            {/*  <div className={styles.cont}>{apiProtocol2 || '-'}</div> */}
            {/* </Item> */}
            <Item
              label="请求方式"
              name="httpRequestMethod"
            >
              <div className={styles.cont}>{httpRequestMethod || '-'}</div>
            </Item>
            <Item
              label="URL"
              name="url"
            >
              <div className={styles.cont}>{url || '-'}</div>
            </Item>

            <Item wrapperCol={{ span: 12 }}>
              <Tabs
                defaultActiveKey="1"
                activeKey={activeTabKey}
                onChange={(e) => { this.setState({ activeTabKey: e }) }}
              >
                <TabPane tab="认证" key="1">
                  <Item
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                    label="类型"
                    name="authType"
                  // rules={[{ required: true, message: '请选择认证类型' }]}
                  // initialValue="noauth"
                  >
                    <div className={styles.cont}>
                      {
                        authType === 'noauth' && '无'
                      }
                      {
                        authType === 'sign' && 'API密钥'
                      }
                      {
                        authType === 'token' && 'Token令牌'
                      }
                      {
                        authType === 'jar' && '自定义认证'
                      }
                    </div>
                  </Item>
                  <Item shouldUpdate noStyle>
                    {authType === 'sign' && (
                      <>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="key"
                          name="accessKey"
                        >
                          <div className={styles.cont}>{accessKey || '-'}</div>
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="value"
                          name="accessSecret"
                        >
                          <div className={styles.cont}>{accessSecret || '-'}</div>
                        </Item>
                      </>
                    )}
                  </Item>
                  <Item shouldUpdate noStyle>
                    {authType === 'token' && (
                      <Item
                        labelCol={{ span: 4 }}
                        wrapperCol={{ span: 20 }}
                        label="Token"
                        name="accessToken"
                      >
                        <div className={styles.cont}>{accessToken || '-'}</div>
                      </Item>
                    )}
                  </Item>
                  <Item shouldUpdate noStyle>
                    {authType === 'jar' && (
                      <>
                        <Item
                          wrapperCol={{ span: 24 }}
                          name="advancedFilePath"
                          rules={[{ required: true, message: '请上传jar包' }]}
                        >
                          <Dragger
                            disabled
                            name="file"
                            // multiple={false}
                            accept=".jar"
                            maxCount={1}
                            action={`${SUAN_PAN}/api/v1/integration/api/http/uploadJar`}
                            headers={{ 'X-Project-Id': getProjectId() }}
                            fileList={fileList}
                            onChange={(info) => {
                              if (info.file.status !== 'uploading') {
                                // console.log(info.file, info.fileList);
                              }
                              if (info.file.status === 'done') {
                                const res = info.file.response
                                if (res.status === 200) {
                                  message.success(`${info.file.name} 上传成功`)
                                  this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: info?.file?.response?.data?.filePath })
                                  // const advancedCacheKey = info?.file?.response?.data?.cacheKey
                                  // const advancedFileName = info?.file?.name || ''
                                } else {
                                  message.warning(res.msg, 3)
                                  info.file.status = 'error'
                                  info.file.response = res.msg || '上传错误'
                                  info.fileList.find((item) => item.uid === info.file.uid).status = 'error'
                                }
                              } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 上传失败.`)
                              }
                              if (info.file.status === 'removed') {
                                this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                              }

                              this.setState({
                                fileList: info?.fileList || [],
                              })
                            }}
                            onRemove={() => {
                              this.dataSourceForm?.current?.setFieldsValue({ advancedFilePath: '' })
                            }}
                            style={{ height: '200px' }}
                          >
                            <p className="ant-upload-drag-icon">
                              <i className="iconfont icon-cunchu" />
                            </p>
                            <p className="ant-upload-text">将文件拖拽至此，或单击直接上传</p>
                            <p className="ant-upload-hint">支持扩展名：jar</p>
                          </Dragger>
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="类名"
                          name="advanceClassReference"
                        >
                          <div className={styles.cont}>{advanceClassReference || '-'}</div>
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="方法名"
                          name="advanceMethodName"
                        >
                          <div className={styles.cont}>{advanceMethodName || '-'}</div>
                        </Item>
                        <Item
                          labelCol={{ span: 4 }}
                          wrapperCol={{ span: 20 }}
                          label="变量有效期"
                          name="expires"
                        // rules={[{ required: true, message: '请输入变量有效期' }]}
                        >
                          {/* <DatePicker */}
                          {/*  disabledDate={this.disabledDate} */}
                          {/*  // value={beginDay && moment(beginDay, 'YYYY-MM-DD')} */}
                          {/*  // onChange={this.handleBeginDay} */}
                          {/*  placeholder="请输入变量有效期" */}
                          {/*  style={{ width: '100%' }} */}
                          {/* /> */}
                          <div className={styles.cont}>{expires || '-'}</div>
                        </Item>
                      </>
                    )}
                  </Item>
                </TabPane>
                <TabPane tab="请求头" key="2">
                  <Item wrapperCol={{ span: 24 }}>
                    <Form ref={this.tableData} component={false}>
                      <ProTable
                        rowKey={() => (Math.random())}
                        loading={false}
                        showQuickJumper={false}
                        showSizeChanger={false}
                        pagination={false}
                        dataSource={requestHeaderData}
                        components={{
                          body: {
                            cell: EditableCell,
                          },
                        }}
                        columns={headerColumns.map(col => {
                          if (!col.editable) {
                            return col
                          }
                          return {
                            ...col,
                            onCell: (record) => ({
                              record,
                              dataIndex: col.dataIndex,
                              title: col.title,
                              inputType: col.inputType,
                              editing: this.state.editingKey === record.key,
                            }),
                          }
                        })}
                        scroll={{ y: 157 }}
                      />
                    </Form>
                  </Item>
                </TabPane>
                <TabPane tab="请求体" key="3">
                  <Item
                    label="类型"
                    name="bodyType"
                  // rules={[{ required: true, message: '请选择请求体类型' }]}
                  // initialValue="application/json"
                  >
                    {/* <Select> */}
                    {/*  <Option value="application/json">application/json</Option> */}
                    {/* </Select> */}
                    <div className={styles.cont}>{contentType || '-'}</div>
                  </Item>
                  <Item shouldUpdate noStyle>
                    {contentType === 'application/json' && (
                      <div className={styles.json_diff_editor}>
                        <CreateDiffEditor
                          readOnly
                          restData={rawJson || ''}
                          ref={this.objectParamsRef}
                          language="json"
                          theme="vs"
                          editorId={this.editorObjectEditId}
                        />
                      </div>
                    )}
                  </Item>
                </TabPane>
              </Tabs>
            </Item>
          </Form>
        </div>
      </div>
    )
  }
}

export default RegisterApiDetail
